import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:multi_shop/services/order_api.dart';
import 'package:multi_shop/utils/index.dart';
import 'package:pinput/pinput.dart';

enum PayMethod {
  balance('余额支付', Icons.account_balance_wallet);

  final String label;
  final IconData icon;
  const PayMethod(this.label, this.icon);
}

class PayDialog extends StatefulWidget {
  final double amount;
  final double balance;
  final String orderNo;

  final Function(PayMethod, String password) onConfirm;

  const PayDialog({
    super.key,
    required this.orderNo,
    required this.amount,
    required this.onConfirm,
    required this.balance,
  });

  @override
  State<PayDialog> createState() => _PayDialogState();
}

class _PayDialogState extends State<PayDialog> {
  PayMethod _selected = PayMethod.balance;
  final TextEditingController _pwdController = TextEditingController();
  final FocusNode _pinFocusNode = FocusNode();

  bool _hasError = false;
  String? _errorText;
  final OrderApi _orderApi = OrderApi();
  PinTheme get _defaultPinTheme => PinTheme(
    width: 48,
    height: 52,
    textStyle: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
    decoration: BoxDecoration(
      border: Border.all(color: Colors.black12),
      borderRadius: BorderRadius.circular(8),
    ),
  );

  @override
  void dispose() {
    _pwdController.dispose();
    _pinFocusNode.dispose();
    super.dispose();
  }

  void _validateAndSubmit() {
    final pwd = _pwdController.text.trim();

    if (pwd.length < 6) {
      setState(() {
        _hasError = true;
        _errorText = '请输入6位支付密码';
      });
      return;
    }
    if (_selected == PayMethod.balance) {
      if (widget.balance < widget.amount) {
        setState(() {
          _hasError = true;
          _errorText = '余额不足';
        });
        return;
      }
    }
    final pwdSign = hmacSha256Hex(key: pwd, message: pwd);
    _orderApi
        .pay(widget.orderNo, _selected.index + 1, pwdSign)
        .then((value) {
          Navigator.pop(context);
          widget.onConfirm(_selected, pwdSign);
          _hasError = false;
          toastCenter("支付成功");
          return;
        })
        .catchError((err) {
          setState(() {
            _hasError = true;
            _errorText = err;
          });
        });
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      insetPadding: const EdgeInsets.symmetric(horizontal: 20),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      backgroundColor: Colors.white,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            /// 标题
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  '支付订单',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                ),
              ],
            ),
            const SizedBox(height: 8),

            /// 支付金额
            Text(
              '￥${widget.amount.toStringAsFixed(2)}',
              style: const TextStyle(
                fontSize: 26,
                fontWeight: FontWeight.bold,
                color: Colors.red,
              ),
            ),
            const SizedBox(height: 16),

            /// 我的余额
            Align(
              alignment: Alignment.centerLeft,
              widthFactor: 2,
              child: Text(
                '我的余额：￥${widget.balance.toStringAsFixed(2)}',
                style: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: Colors.black,
                ),
              ),
            ),
            const SizedBox(height: 16),

            /// 支付方式选择
            Column(
              children: PayMethod.values.map((method) {
                return RadioListTile<PayMethod>(
                  value: method,
                  groupValue: _selected,
                  title: Text(method.label),
                  secondary: Icon(method.icon, color: Colors.blue),
                  onChanged: (value) {
                    if (value != null) {
                      setState(() => _selected = value);
                    }
                  },
                );
              }).toList(),
            ),
            const SizedBox(height: 12),

            /// Pinput 输入支付密码
            Pinput(
              length: 6,
              controller: _pwdController,
              focusNode: _pinFocusNode,
              defaultPinTheme: _defaultPinTheme,
              obscureText: true,
              obscuringCharacter: '•',
              keyboardType: TextInputType.number,
              closeKeyboardWhenCompleted: true,
              showCursor: true,
              errorPinTheme: _defaultPinTheme.copyWith(
                decoration: _defaultPinTheme.decoration!.copyWith(
                  border: Border.all(color: Colors.red, width: 2),
                ),
              ),
              forceErrorState: _hasError,

              /// 输入变动时重置错误提示
              onChanged: (value) {
                if (_hasError) {
                  setState(() {
                    _hasError = false;
                    _errorText = null;
                  });
                }
              },
            ),

            /// 错误提示
            if (_hasError && _errorText != null)
              Padding(
                padding: const EdgeInsets.only(top: 8),
                child: Text(
                  _errorText!,
                  style: const TextStyle(color: Colors.red, fontSize: 13),
                ),
              ),

            const SizedBox(height: 16),

            /// 确认按钮
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                minimumSize: const Size.fromHeight(48),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              onPressed: _validateAndSubmit,
              child: const Text('确认支付'),
            ),
          ],
        ),
      ),
    );
  }
}
